package org.xiyu.yee.beacon_anti_phantom.particle;

import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.monster.Phantom;
import net.minecraft.world.phys.Vec3;
import org.xiyu.yee.beacon_anti_phantom.beacon.BeaconManager;
import org.xiyu.yee.beacon_anti_phantom.Constants;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class BeaconAttackEffectManager {
    private static BeaconAttackEffectManager instance;
    
    // 存储正在被攻击的幻翼信息
    private final Map<UUID, AttackInfo> attackingPhantoms = new ConcurrentHashMap<>();
    
    private BeaconAttackEffectManager() {}
    
    public static BeaconAttackEffectManager getInstance() {
        if (instance == null) {
            instance = new BeaconAttackEffectManager();
        }
        return instance;
    }
    
    /**
     * 开始攻击幻翼的效果
     */
    public void startAttackEffect(Phantom phantom, BlockPos beaconPos, ServerLevel level) {
        UUID phantomId = phantom.getUUID();
        
        // 给幻翼添加一个特殊标签，防止被其他系统移除
        phantom.addTag("beacon_attacking");
        
        attackingPhantoms.put(phantomId, new AttackInfo(phantom, beaconPos, level, System.currentTimeMillis()));
        Constants.LOG.info("Started beacon attack effect on phantom {} from beacon at {}", phantomId, beaconPos);
    }
    
    /**
     * 检查幻翼是否正在被攻击
     */
    public boolean isBeingAttacked(UUID phantomId) {
        return attackingPhantoms.containsKey(phantomId);
    }
    
    /**
     * 更新攻击效果
     */
    public void tick(ServerLevel level) {
        Iterator<Map.Entry<UUID, AttackInfo>> iterator = attackingPhantoms.entrySet().iterator();
        
        while (iterator.hasNext()) {
            Map.Entry<UUID, AttackInfo> entry = iterator.next();
            UUID phantomId = entry.getKey();
            AttackInfo info = entry.getValue();
            
            // 检查幻翼是否还存在
            if (info.phantom.isRemoved()) {
                Constants.LOG.debug("Phantom {} was removed externally during attack", phantomId);
                iterator.remove();
                continue;
            }
            
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - info.startTime;
            
            // 每tick生成粒子束效果，让效果更连续
            spawnBeamParticles(info.beaconPos, info.phantom.position(), level);
            
            // 添加调试信息
            if (elapsedTime % 200 == 0) { // 每200ms打印一次
                Constants.LOG.debug("Attacking phantom {} for {}ms", phantomId, elapsedTime);
            }
            
            // 1秒后移除幻翼
            if (elapsedTime >= 1000) {
                Constants.LOG.info("Beacon attack complete! Removing phantom {} after {} ms", phantomId, elapsedTime);
                // 移除标签
                info.phantom.removeTag("beacon_attacking");
                // 移除幻翼
                info.phantom.discard();
                iterator.remove();
            }
        }
    }
    
    /**
     * 生成从信标到幻翼的粒子束
     */
    private void spawnBeamParticles(BlockPos beaconPos, Vec3 phantomPos, ServerLevel level) {
        Vec3 beaconVec = Vec3.atCenterOf(beaconPos);
        Vec3 direction = phantomPos.subtract(beaconVec).normalize();
        double distance = beaconVec.distanceTo(phantomPos);
        
        // 沿着直线生成粒子
        int particleCount = (int) Math.max(10, distance);
        for (int i = 0; i < particleCount; i++) {
            double progress = (double) i / particleCount;
            Vec3 particlePos = beaconVec.add(direction.scale(distance * progress));
            
            // 使用发光的粒子效果
            level.sendParticles(ParticleTypes.END_ROD, 
                particlePos.x, particlePos.y, particlePos.z, 
                1, 0.0, 0.0, 0.0, 0.0);
            
            // 添加一些装饰性粒子
            if (i % 3 == 0) {
                level.sendParticles(ParticleTypes.ELECTRIC_SPARK, 
                    particlePos.x, particlePos.y, particlePos.z, 
                    2, 0.1, 0.1, 0.1, 0.05);
            }
        }
        
        // 在幻翼位置生成爆炸效果粒子
        level.sendParticles(ParticleTypes.CRIT, 
            phantomPos.x, phantomPos.y, phantomPos.z, 
            5, 0.3, 0.3, 0.3, 0.1);
    }
    
    /**
     * 找到最近的信标
     */
    public BlockPos findNearestBeacon(BlockPos phantomPos) {
        BlockPos nearestBeacon = null;
        double nearestDistance = Double.MAX_VALUE;
        
        for (Map.Entry<BlockPos, Integer> entry : BeaconManager.getInstance().getActiveBeacons().entrySet()) {
            BlockPos beaconPos = entry.getKey();
            double distance = Math.sqrt(Math.pow(phantomPos.getX() - beaconPos.getX(), 2) + 
                                      Math.pow(phantomPos.getZ() - beaconPos.getZ(), 2));
            
            int radius = BeaconManager.getInstance().getBeaconRadius(beaconPos);
            if (distance <= radius && distance < nearestDistance) {
                nearestDistance = distance;
                nearestBeacon = beaconPos;
            }
        }
        
        return nearestBeacon;
    }
    
    /**
     * 攻击信息类
     */
    private static class AttackInfo {
        final Phantom phantom;
        final BlockPos beaconPos;
        final ServerLevel level;
        final long startTime;
        
        AttackInfo(Phantom phantom, BlockPos beaconPos, ServerLevel level, long startTime) {
            this.phantom = phantom;
            this.beaconPos = beaconPos;
            this.level = level;
            this.startTime = startTime;
        }
    }
}
